/**
 * @fileOverview
 * @author iNahoo
 * @since 2019/11/12.
 */

const __R = require('robotjs');
const {sleep} = require('../utils');

function randomOffset(r = 10) {
    return Math.floor(Math.random() * r) - r / 2;
}

class FixedR {
    constructor(R) {
        this.R = R;
        const {width} = R.getScreenSize();
        const expectWidht = 3840;
        this.r = width / expectWidht;
    }

    moveMouse(x, y, rx = 10, ry = 10) {
        return this.R.moveMouse(
            x * this.r + randomOffset(rx),
            y * this.r + randomOffset(ry)
        )
    }

    mouseClick(...args) {
        return this.R.mouseClick(...args)
    }

    getMousePos() {
        const p = this.R.getMousePos();
        return {
            x: Math.floor(p.x / this.r),
            y: Math.floor(p.y / this.r)
        }
    }
}

const FR = new FixedR(__R);

/**
 * @type {Array<Task>}
 */
const queue = [];

async function loop() {
    while (true) {
        await sleep(200);
        if (queue.length === 0) {
            continue;
        }

        const task = queue.shift();
        await task.run();
        await task.done();
    }
}

class Task {
    constructor(run, done) {
        this.run = run;
        this.done = done;
    }
}

class MouseManager {

    constructor() {
        this.__mousePosStack = [];
    }

    save() {
        this.__mousePosStack.push(FR.getMousePos());
    }

    restore() {
        const {x, y} = this.__mousePosStack.pop();
        FR.moveMouse(x, y);
    }

    /**
     * @param x
     * @param y
     * @param rx
     * @param ry
     * @return {Promise}
     */
    async click({x, y, rx, ry}) {
        return new Promise(r => {
            queue.push(new Task(async () => {
                FR.moveMouse(x, y, rx, ry);
                await sleep(50);
                FR.mouseClick();
                await sleep(50);
                await MouseManager.safeBlur();
            }, r))
        });
    }

    static safeBlur() {
        const x = 51;
        const y = 1918;
        FR.moveMouse(x, y);
        FR.mouseClick();
    }
}


loop().then(() => {

});

module.exports = new MouseManager();